// 当前查询条件和分页信息
let currentQuery = {
  pageNum: 1,
  pageSize: 10
};

// 当前查询结果
let currentResult = {
  total: 0,
  list: []
};

// 初始化页面
window.onload = async function() {
  // 确保token已加载
  const currentToken = loadToken() || token;
  if (!currentToken) {
    window.location.href = 'login.html';
    return;
  }
  
  // 加载用户信息
  await loadUserInfo();
  
  // 默认加载最近24小时的日志
  const now = new Date();
  const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
  
  document.getElementById('startTime').value = formatDateTimeLocal(yesterday);
  document.getElementById('endTime').value = formatDateTimeLocal(now);
  
  // 执行查询
  await onQueryLogs(null);
};

// 加载用户信息
async function loadUserInfo() {
  const resp = await request(api.me);
  if (resp.ok && resp.data && resp.data.success && resp.data.data) {
    const userInfo = resp.data.data;
    document.getElementById('admin-name').textContent = userInfo.name || userInfo.username;
    document.getElementById('admin-role').textContent = userInfo.role;
  }
}

// 格式化日期时间为datetime-local格式
function formatDateTimeLocal(date) {
  // 直接格式化为本地时间，不进行时区转换
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 查询日志处理函数
async function onQueryLogs(e) {
  if (e) {
    e.preventDefault();
    currentQuery.pageNum = 1;
  }
  
  // 获取查询条件
  const queryForm = document.getElementById('logQueryForm');
  const formData = new FormData(queryForm);
  
  // 构建查询对象
  const queryParams = {
    pageNum: currentQuery.pageNum,
    pageSize: currentQuery.pageSize
  };
  
  // 填充查询参数
  for (let [key, value] of formData.entries()) {
    if (value !== '') {
      // 特殊处理日期时间格式
      if (key === 'startTime' || key === 'endTime') {
        // 发送北京时间格式（UTC+8）
        if (value) {
          // datetime-local输入的值是本地时间，转换为北京时间格式
          const localDate = new Date(value);
          // 格式化为北京时间（UTC+8）的ISO字符串
          const beijingTime = new Date(localDate.getTime() + (8 * 60 * 60 * 1000));
          queryParams[key] = beijingTime.toISOString().replace('Z', '+08:00');
        }
      } else if (key === 'userId') {
        queryParams[key] = parseInt(value);
      } else if (key === 'success') {
        queryParams[key] = value === 'true';
      } else {
        queryParams[key] = value;
      }
    }
  }
  
  // 保存当前查询条件
  currentQuery = queryParams;
  
  console.log('发送查询参数:', queryParams);
  
  // 执行查询
  const resp = await request(api.queryLogs, {
    method: 'POST',
    body: JSON.stringify(queryParams)
  });
  
  // 处理查询结果
  if (resp.ok && resp.data) {
    currentResult = resp.data;
    renderLogsTable();
    updatePagination();
  } else {
    showResult('logsTableBody', resp.data || { success: false, message: '查询日志失败' });
  }
}

// 渲染日志列表
function renderLogsTable() {
  const tableBody = document.getElementById('logsTableBody');
  const totalCount = document.getElementById('totalCount');
  
  // 更新总记录数
  totalCount.textContent = currentResult.total || 0;
  
  // 清空表格
  tableBody.innerHTML = '';
  
  // 如果没有数据，显示空提示
  if (!currentResult.list || currentResult.list.length === 0) {
    const emptyRow = document.createElement('tr');
    emptyRow.innerHTML = `<td colspan="11" style="text-align: center;">暂无数据</td>`;
    tableBody.appendChild(emptyRow);
    return;
  }
  
  // 渲染日志数据
  currentResult.list.forEach(log => {
    const row = document.createElement('tr');
    
    // 根据日志类型和状态设置样式
    let statusClass = '';
    if (log.success === false) {
      statusClass = 'error-row';
    } else if (log.level === 'ERROR' || log.level === 'FATAL') {
      statusClass = 'error-row';
    } else if (log.level === 'WARN') {
      statusClass = 'warning-row';
    }
    
    row.className = statusClass;
    
    // 格式化时间
    const formattedTime = log.ts ? new Date(log.ts).toLocaleString('zh-CN') : '';
    
    // 构建关联ID信息
    let relatedIds = '';
    if (log.requestId) {
      relatedIds = `请求ID: ${log.requestId.substring(0, 8)}...`;
    } else if (log.deviceId) {
      relatedIds = `设备ID: ${log.deviceId}`;
    } else if (log.robotId) {
      relatedIds = `机器人ID: ${log.robotId}`;
    } else if (log.taskId) {
      relatedIds = `任务ID: ${log.taskId}`;
    }
    
    // 设置行内容
    row.innerHTML = `
      <td>${log.id}</td>
      <td>${formattedTime}</td>
      <td>${log.logType || ''}</td>
      <td>${log.level || ''}</td>
      <td>${log.module || ''}</td>
      <td>${log.action || ''}</td>
      <td>${log.userId || '-'}</td>
      <td>${log.success === true ? '成功' : log.success === false ? '失败' : '-'}</td>
      <td class="message-cell">${log.message || ''}</td>
      <td>${relatedIds}</td>
      <td>
        <button class="btn-view" onclick="viewLogDetail(${log.id})">查看</button>
      </td>
    `;
    
    tableBody.appendChild(row);
  });
}

// 更新分页控件
function updatePagination() {
  const currentPageElem = document.getElementById('currentPage');
  const prevPageBtn = document.getElementById('prevPage');
  const nextPageBtn = document.getElementById('nextPage');
  
  // 更新当前页码
  currentPageElem.textContent = currentQuery.pageNum;
  
  // 更新上一页按钮状态
  prevPageBtn.disabled = currentQuery.pageNum <= 1;
  
  // 更新下一页按钮状态
  const totalPages = Math.ceil((currentResult.total || 0) / currentQuery.pageSize);
  nextPageBtn.disabled = currentQuery.pageNum >= totalPages;
}

// 上一页
function onPrevPage() {
  if (currentQuery.pageNum > 1) {
    currentQuery.pageNum--;
    onQueryLogs(null);
  }
}

// 下一页
function onNextPage() {
  const totalPages = Math.ceil((currentResult.total || 0) / currentQuery.pageSize);
  if (currentQuery.pageNum < totalPages) {
    currentQuery.pageNum++;
    onQueryLogs(null);
  }
}

// 改变每页显示数量
function onChangePageSize() {
  const pageSizeSelect = document.getElementById('pageSize');
  currentQuery.pageSize = parseInt(pageSizeSelect.value);
  currentQuery.pageNum = 1;
  onQueryLogs(null);
}

// 查看日志详情
async function viewLogDetail(logId) {
  const resp = await request(api.getLogById(logId));
  
  if (resp.ok && resp.data) {
    const logDetailContent = document.getElementById('logDetailContent');
    // 格式化JSON，提高可读性
    logDetailContent.textContent = JSON.stringify(resp.data, null, 2);
    
    // 显示模态框
    const logDetailModal = document.getElementById('logDetailModal');
    logDetailModal.classList.remove('hidden');
  } else {
    alert('获取日志详情失败: ' + (resp.data?.message || '未知错误'));
  }
}

// 关闭日志详情模态框
function closeLogDetailModal() {
  const logDetailModal = document.getElementById('logDetailModal');
  logDetailModal.classList.add('hidden');
}

// 重置查询表单
function resetQueryForm() {
  const queryForm = document.getElementById('logQueryForm');
  queryForm.reset();
  
  // 重置当前查询条件
  currentQuery = {
    pageNum: 1,
    pageSize: currentQuery.pageSize
  };
}

// 点击模态框外部关闭
window.onclick = function(event) {
  const modal = document.getElementById('logDetailModal');
  if (event.target === modal) {
    closeLogDetailModal();
  }
}